﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CALTypeLib;
using Logica.WebServices_BCR;
using Entidades;
namespace Logica.InfoImage_Folder
{
    public class IIF_Manager:IIF_Connection
    {
        private bool searched = true;
        public IIF_Manager()
        {
            if (!(base.CreateIIFClient(Configuration.IIFUser, Configuration.IIFPassword, Configuration.IIFDomain)))
                throw new Exception("Imposible abrir conexion con InfoImage, favor revisar las Bitacoras");
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="objID">Object_Id por el que se reclasificará el documento.</param>
        public bool Reclasify(string objID,string newClass)
        {
            
             CALDocument document = SearchDocument(objID);//busca el documento

            if (document != null)
            {
                Services.sendLog(638, "Reclasificando documento con OBJECT_ID[" + objID + "]", Services.errorType.Information_Message);
                document.Reclassify(newClass, ReclassifyConstants.calReclassifyRetainFormData);
                document.Save();
                document.Close(CloseConstants.calCloseSaveChanges);
                Services.sendLog(292, "Proceso de Reclasificacion finalizado con exito", Services.errorType.Information_Message);
                return true;
            }
            else 
                return false;            
        }

        public CALDocument SearchDocument(string objID)
        {
            /*
            CALIndexFields Object_ID = new CALIndexFields();
            Object_ID.set_Value("OBJECT_ID", objID);

            Services.sendLog(636, "Buscando documento con OBJECT_ID["+objID+"] en InfoImage", Services.errorType.Information_Message);

            CALQueryResults resultado = (CALQueryResults)
                    calClient.Query("", ObjTypeConstants.calObjTypeDocument,
                                      LocationConstants.calLocationDomain & LocationConstants.calLocationArchive, 100, Object_ID);//se debe hacer para buscar tambien en enterprise
            */
            Services.sendLog(291, "Buscando Documento ["+objID+"]", Services.errorType.Information_Message);
           
            CALObjID ID = new CALObjID();
            ID.InternalName = objID;
            calWorkitemWorkstepList = (CALWorkitemWorkstepList)calClient.FindInWorkflow(ID);
            
            
            
            if (/*resultado.Count > 0*/calWorkitemWorkstepList.Count>0)
            {
                try
                {
                    Services.sendLog(291, "Documento encontrado.", Services.errorType.Information_Message);
                    var gCalEnumItemFound = calWorkitemWorkstepList.Item[1];//resultado.Item[1];
                    calWorkitemInfoFound = (CALWorkitemInfo)gCalEnumItemFound.Info;
                    //  MessageBox.Show("Cantidad: " + resultado.Count + "ObjectID: " + calWorkitemInfoFound.ObjID.InternalName);


                    var gCalClientListItemFound = (CALClientListItem)gCalEnumItemFound.Retrieve(RetrieveConstants.calRetrieveRetain);
                    CALDocument documento = (CALDocument)gCalClientListItemFound.Open(OpenConstants.calOpenReadWrite | OpenConstants.calOpenArchive);
                    searched = false;
                    return documento;
                }
                catch (Exception e)
                {
                    Services.sendLog(217, "Workitem [" + objID + "] no encontrado en IIF. "+e.Message, Services.errorType.Error_Message);
                    return null;
                }
                
                
            }
            else
            {
                Services.sendLog(217, "Documento no encontrado [Favor revisar los permisos del usuario: "+Configuration.IIFUser+"]", Services.errorType.Error_Message);
                return null;
                //No se encontraron documentos coincidentes con el OBJECT_ID
            }
        }
      
        public bool SendToWorkflow(string objID,string outputQueue)
        {
            if (outputQueue.Equals(""))
                return SendToWorkflow(objID);//envio a la cola default
            else
            {
                CALDocument document=null;
                if (searched)
                {
                    document = SearchDocument(objID);
                    document.Close(CloseConstants.calCloseSaveChanges);
                }
                if ((document != null) || (!searched))
                {
                    Services.sendLog(615, "Workstep [" + outputQueue + "] asignado exitosamente.", Services.errorType.Information_Message);
                    try
                    {
                        calQueue.Name = outputQueue;
                        calQueue.Type = QueueTypeConstants.calQueueTypeWorkstep;
                        calClientListItem = calClientList.Item[1, ObjTypeConstants.calObjTypeDocument];
                        calClientListItem.Send(calQueue, SendConstants.calSendDiscard);
                    }
                    catch (Exception e)
                    {
                        Services.sendLog(616, "Error al eviar el Documento ["+objID +"] a la cola ["+outputQueue+"]", Services.errorType.Error_Message,e);
                        return false;
                    }
                    Services.sendLog(617, "Workitem [" + objID + "] enviado a la cola [" + outputQueue + "].", Services.errorType.Information_Message);
                    
                    return true;                                       
                }
                else 
                {
                    Services.sendLog(215, "Workitem [" + objID + "] no encontrado en IIF", Services.errorType.Information_Message);
                    return false; 
                }
            }
 
        }

     
        public bool SendToWorkflow(string objID)
        {
            CALDocument document = null;
            if (searched)
            {
                document = SearchDocument(objID);
                document.Close(CloseConstants.calCloseSaveChanges);
            }
            if ((document != null)||(!searched))
            {
                Services.sendLog(616, "Enviando workitem [" + objID + "] a la cola  [Default].", Services.errorType.Information_Message);
                try
                {
                    calClientListItem = calClientList.Item[1, ObjTypeConstants.calObjTypeDocument];
                    calClientListItem.SendToDefault(SendConstants.calSendDiscard);
                }
                catch (Exception e)
                {
                    Services.sendLog(616, "Error al eviar el Documento ["+objID +"] a la cola [Default]", Services.errorType.Error_Message,e);
                    return false;
                }
                Services.sendLog(285, "Workitem [" + objID + "] enviado a la cola  [Default] exitosamente.", Services.errorType.Information_Message);
                return true;
            }
            else{
                Services.sendLog(215, "Workitem [" + objID + "] no encontrado en IIF", Services.errorType.Information_Message);
                return false;
            }
        }

    }
}
